﻿using Kxx_Domain.DNS;
using Kxx_Log.Log;
using Kxx_Save.DNS;
using Kxx_Services.DNS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Kxx_Task.DNS
{
    public class DomainRecordTaskExecModel : DomainRecordTaskModel, IDisposable
    {
        DNSService dnsService;
        private bool isService;
        public DomainRecordTaskExecModel(bool isService)
        {
            this.isService = isService;

            dnsService = new DNSService();

            RecordNotifyTask.Start();

            RecordTask.Start();
        }

        private TaskStatus recordTaskStatus;
        /// <summary>
        /// 任务状态
        /// </summary>
        public TaskStatus RecordTaskStatus
        {
            get
            {
                if (!IsRun) return TaskStatus.WaitingForActivation;
                return recordTaskStatus;
            }
            set { recordTaskStatus = value; }
        }

        /// <summary>
        /// 本机记录值（IP）
        /// </summary>
        public string Value
        {
            get
            {
                return DNSLoad.NativeIPAddress;
            }
        }

        #region 任务
        private static readonly object objStatus = new object();
        private Task recordNotifyTask;
        /// <summary>
        /// 刷新状态线程
        /// </summary>
        public Task RecordNotifyTask
        {
            get
            {
                if (recordNotifyTask == null)
                {
                    lock (objStatus)
                    {
                        if (recordNotifyTask == null)
                        {
                            recordNotifyTask = new Task(NotifyRefresh);
                        }
                    }
                }
                return recordNotifyTask;
            }
        }

        private static readonly object obj = new object();
        private Task recordTask;
        /// <summary>
        /// 定时任务线程
        /// </summary>
        public Task RecordTask
        {
            get
            {
                if (recordTask == null)
                {
                    lock (obj)
                    {
                        if (recordTask == null)
                        {
                            recordTask = new Task(ScheduledTask);
                        }
                    }
                }
                return recordTask;
            }
        }

        /// <summary>
        /// 通知刷新
        /// </summary>
        private void NotifyRefresh()
        {
            while (!_disposed)
            {
                //任务状态
                RecordTaskStatus = RecordTask.Status;

                Thread.Sleep(NotifyFrequency * 1000);
            }
        }

        /// <summary>
        /// 定时任务
        /// </summary>
        private void ScheduledTask()
        {
            Thread.Sleep(TaskWaitTime * 1000);
            while (!_disposed)
            {
                if (IsRun)
                {
                    if ((isService && DNSLoad.IsWindowsServiceRunning(DNSLoad.serverName)) || (!isService && !DNSLoad.IsWindowsServiceRunning(DNSLoad.serverName)))
                    {
                        dnsService.UpdateDomainRecord(RecordId, RR, Type, DNSLoad.NativeIPAddress);
                    }
                }

                Thread.Sleep(TaskWaitTime * 1000);
            }
        }
        #endregion

        #region 资源释放
        private bool _disposed;
        private object _obj = new object();
        public void Dispose()
        {
            Dispose(true);
            // 请求公共语言运行时不要调用该对象上的终结器（在C#中就是指不要调用析构函数）
            GC.SuppressFinalize(this);
        }

        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);
        protected virtual void Dispose(bool disposing)
        {
            // 保证线程安全
            lock (_obj)
            {
                if (!_disposed)
                {
                    if (disposing)
                    {
                        // Release managed resources
                    }

                    // Release unmanaged resources

                    _disposed = true;
                }
            }
        }
        public void Close()
        {
            Dispose();
        }
        ~DomainRecordTaskExecModel()
        {
            Dispose(false);
        }
        #endregion
    }
}
